package com.smart.common.base.handler;

import com.smart.common.base.result.ResponseResult;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@RestControllerAdvice
public class GlobalHandlerException {
    /**
     * ConstraintViolationException  get请求单个参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult<Object> handler(ConstraintViolationException ex) {
        List<String> errors = new ArrayList<>();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        constraintViolations.forEach(constraintViolation -> {
            errors.add(constraintViolation.getMessage());
        });
        return ResponseResult.error();
    }

    /**
     * MethodArgumentNotValidException @RequestBody注解抛出的异常
     * BindException  普通的对象参数校验 抛出异常信息
     *
     * @param ex
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public ResponseResult<Object> handler(BindException ex) {
        StringBuffer sb = new StringBuffer();
        List<ObjectError> allErrors = ex.getAllErrors();
        allErrors.forEach(error -> {
            sb.append(error.getDefaultMessage()).append(",");
        });
        return ResponseResult.error();
    }
}
